package application;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

import menu.Menu;
import game.Game;


public class Application{
	private Window window;
	
	private Game		game;
	private Menu		menu;
	
	private long lastTime;
	
	/**
	 * Creates application
	 */
	
	public Application(){
		window = new Window(Configuration.WINDOW_WIDTH, Configuration.WINDOW_HEIGHT, Configuration.WINDOW_TITLE);
		
		menu = new Menu();
		
		try {
			Keyboard.create();
			Mouse.create();
		} catch (LWJGLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Run application
	 */
	
	public void run(){
		menu.run();
		
		lastTime = System.currentTimeMillis();
		while(window.running()){
			window.clear();
			
			keyboardController();
			mouseController();
			
			if(game != null) game.update(System.currentTimeMillis() - lastTime);
			menu.update(System.currentTimeMillis() - lastTime);
			handleMenuEvent(menu.getMenuEvent());
			
			
			lastTime = System.currentTimeMillis();
			
			
			if(game != null) game.redraw();
			menu.redraw();

			window.update();
		}
	}
	
	private void handleMenuEvent(MenuEvents event){
		switch(event){
		case NULL:
			break;
		case EXIT:
			System.exit(0);
			break;
		case START_GAME:
			this.menu.resetMenuEvent();
			this.game = new Game();
			this.game.run();
			break;
		default:
			break;
		}
	}
	
	private void keyboardController(){
		while(Keyboard.next()){
			KeyboardEvent event = new KeyboardEvent(Keyboard.getEventKey(), Keyboard.getEventKeyState());
			
			menu.handleKeyboardEvents(event);
			
			if(game != null){
				game.handleKeyboardEvents(event);
			}
		}
	}
	
	private void mouseController(){
		while(Mouse.next()){
			MouseEvent event = new MouseEvent(Mouse.getX(), Mouse.getY(),Mouse.getEventButton(), Mouse.getEventButtonState());
			
			menu.handleMouseEvents(event);
			
			if(game != null){
				game.handleMouseEvents(event);
			}
		}
	}

}
